﻿using System;
using System.Data.Services.Client;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Xml.Linq;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;

namespace EncryptDecrypt
{
    public abstract class EncryptableTableBase : TableServiceContext
    {
        protected AzureTableCrypto TableCrypto { get; set; }
        
        /// <summary>
        /// Get the desired encryption version to use. Entities that are added or updated will be written with this version.
        /// Entities may be read using any version that is still available in the table.
        /// If this property returns null, then both encryption and decryption will be disabled
        /// </summary>
        protected abstract int? EncryptionVersion { get; }

        public EncryptableTableBase(CloudStorageAccount storageAccount)
        : base(storageAccount.TableEndpoint.AbsoluteUri, storageAccount.Credentials)
        {
            if (this.EncryptionVersion.HasValue)
            {
                this.TableCrypto = new AzureTableCrypto(storageAccount);
                this.WritingEntity += new EventHandler<ReadingWritingEntityEventArgs>(DataServiceContextEx_WritingEntity);
                this.ReadingEntity += new EventHandler<ReadingWritingEntityEventArgs>(DataServiceContextEx_ReadingEntity);
            }
        }

        private void DataServiceContextEx_ReadingEntity(object sender, ReadingWritingEntityEventArgs e)
        {
            EncryptableTableServiceEntity entity = e.Entity as EncryptableTableServiceEntity;
            if (entity != null && entity.EncryptionVersion.HasValue && entity.EncryptionVersion.Value > 0)
            {
                this.TableCrypto.DecryptObject(entity.EncryptionVersion.Value, entity);
            }
            //foreach (PropertyInfo property in e.Entity.GetType().GetProperties())
            //{
            //    object[] transparentEncryptAttributes = property.GetCustomAttributes(typeof(EncryptAttribute), false);
            //    if (transparentEncryptAttributes.Length > 0 && property.PropertyType == typeof(string))
            //    {
            //        string propertyValue = (string)property.GetValue(e.Entity, null);
            //        propertyValue = azCrypto.DecryptString(propertyValue, 0);
            //        property.SetValue(e.Entity, propertyValue, null);
            //    }
            //}
        }

        private static readonly XNamespace metadataNamespace = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata";
        private static readonly XNamespace dataServicesNamespace = "http://schemas.microsoft.com/ado/2007/08/dataservices";
        private static readonly XName xnEntityProperties = metadataNamespace + "properties";
        private static readonly XName encryptionVersionElementName = dataServicesNamespace + "EncryptionVersion";
        private static readonly XName nullAttributeName = metadataNamespace + "null";
                
        private void DataServiceContextEx_WritingEntity(object sender, ReadingWritingEntityEventArgs e)
        {
            EncryptableTableServiceEntity entity = e.Entity as EncryptableTableServiceEntity;
            if (entity != null)
            {
                entity.EncryptionVersion = this.EncryptionVersion;
                
                // e.Data gives you the XElement for the Serialization of the Entity 
                //Using XLinq  , you can  add/Remove properties to the element Payload  
                
                XElement xePayload = null;
                foreach (PropertyInfo property in e.Entity.GetType().GetProperties())
                {
                    //object[] doNotSerializeAttributes = property.GetCustomAttributes(typeof(DoNotSerializeAttribute), false);
                    //if (doNotSerializeAttributes.Length > 0)
                    //{
                    //    if (xePayload == null)
                    //    {
                    //        xePayload = e.Data.Descendants().Where<XElement>(xe => xe.Name == xnEntityProperties).First<XElement>();
                    //    }
                    //    //The XName of the property we are going to remove from the payload
                    //    XName xnProperty = dataServicesNamespace + property.Name;
                    //    //Get the Property of the entity  you don't want sent to the server
                    //    XElement xeRemoveThisProperty = xePayload
                    //                   .Descendants()
                    //                   .Where<XElement>(xe => xe.Name == xnProperty)
                    //                   .First<XElement>();
                    //    //Remove this property from the Payload sent to the server 
                    //    xeRemoveThisProperty.Remove();
                    //}
                    object[] transparentEncryptAttributes = property.GetCustomAttributes(typeof(EncryptAttribute), false);
                    if (transparentEncryptAttributes.Length > 0)
                    {
                        if (xePayload == null)
                        {
                            xePayload = e.Data.Descendants(xnEntityProperties).FirstOrDefault();
                            if (xePayload == null)
                            {
                                //This shouldn't happen, but if it does we'll just bail out.
                                return;
                            }
                        }
                        
                        //The XName of the property we are going to encrypt from the payload
                        XName xnProperty = dataServicesNamespace + property.Name;
                        XElement xeEncryptThisProperty = xePayload.Descendants(xnProperty).First();
                        if (xeEncryptThisProperty == null)
                        {
                            //Couldn't find the value in the XML
                            continue;
                        }

                        //Encrypt the property 
                        string propertyValue = xeEncryptThisProperty.Value;
                        if (!string.IsNullOrEmpty(propertyValue))
                        {
                            byte[] cryptedBytes = this.TableCrypto.EncryptString(this.EncryptionVersion.Value, propertyValue);
                            xeEncryptThisProperty.Value = Convert.ToBase64String(cryptedBytes);
                        }
                    }
                }

                //Set the EncryptionVersion element
                if (xePayload != null)
                {
                    //Get the Property of the entity you want to encrypt on the server
                    XElement xVersionElement = xePayload.Descendants(encryptionVersionElementName).First();
                    xVersionElement.Value = this.EncryptionVersion.Value.ToString(CultureInfo.InvariantCulture);

                    //If the EncyptedVersion element had the "null" attribute applied to it, then remove that.
                    xVersionElement.Attributes(nullAttributeName).Remove();
                }
            }
        }
    }
}